<template>
	<view>

		  <!-- <getlocation ></getlocation>	 -->
		<view class="area-header">
			<view class="header-select flex-row justify-between ">
				<view class="select-region flex-row justify-between">
							<getlocation  ref="getlocation" :autoLocation="false" :region="region"></getlocation>
							<text @tap="$refs.getlocation.oncity();" data-v-137d5072="" class="flex f-a-c f-j-c myicon myicon-arrow-down f10-size t-color-b"></text>

				</view>
				<view class="select-input">
					<text class="input_holder" style="margin: 0 10px;">|</text>
					<input v-model="keyword" @input="input" placeholder-class="input_holder" placeholder="请输入地点" />
					<uni-icons type="search" size="22" style="margin-right: 15rpx;" color="#D8D8D8"></uni-icons>
				</view>

			</view>
		</view>

		<!-- 	<view class="" >
				<view class="current_position">
					<view>
	
						<text class="position_text">当前位置</text>
					</view>
				</view>
				<view class="position_ul">
					<view>
						<text data-v-137d5072="" class="flex f-a-c f-j-c myicon myicon-weizhi f14-size t-color-y1"></text>
					</view>
					<view class="address">
			
						<text class="current-address" @click="checkcurrent(currentaddress)">{{currentaddress}}</text>
					</view>
					<view class="dingweis_div" @click="getMyLocation">

						<text data-v-137d5072="" class="flex f-a-c f-j-c myicon myicon-weizhi f14-size t-color-y1"></text>
						<text>{{po_tips}}</text>
					</view>

				</view>
			</view> -->
			<!-- 	<view class="dingwei">
					<view class="dingwei_Tips">
						当前定位
					</view>
					<view class="dingwei_city">
						<view class="dingwei_city_one">
							{{currentaddress}}
						</view>
						<view class="dingweis_div" @click="getWarpweft">

									<text @tap="$refs.getlocation.oncity();" data-v-137d5072="" class="flex f-a-c f-j-c myicon myicon-weizhi f14-size t-color-y1"></text>
							<text>{{po_tips}}</text>
						</view>
					</view>
				</view>		  -->

		<view class="area-site">
			<view>
				<view class="current_position">
					<view>
						<!-- <image src="@/static/images/task/positioning.png" class="position_img"></image> -->
						<text class="position_text">搜索结果</text>
					</view>
				</view>
				<view @click="checkdizhi(item,true)" v-for="(item,index) in searchResults" :key="item.id" class="position_ul 1">
					<view>
			<text data-v-137d5072="" class="flex f-a-c f-j-c myicon myicon-weizhi f14-size t-color-y1"></text>
					</view>
					<view class="address">
						<text class="address-name">{{item.name}}</text>
						<text class="current-address">{{item.district}}{{item.address}}</text>
					</view>
					<view class="distance_text">
						<text>{{item.distance}}</text>
					</view>
				</view>
			</view>
		</view>

		<view class="history-content" v-if="searchResults.length === 0">
			<view class="current_position">
				<view>
					<image src="@/static/images/task/history.png" class="position_img"></image>
					<text class="position_text">历史记录</text>
				</view>
				<view @click="clearHistory" class="clear_history">清空</view>
			</view>

			<view v-if="historyList.length===0" class="history_none" style="padding: 20px;">
				暂无历史记录
			</view>
			<view>
				<view  @click="checkdizhi(item,false)"  v-for="(item,index) in historyList" :key="item.id" class="position_ul 2">
					<view>


						<text data-v-137d5072="" class="flex f-a-c f-j-c myicon myicon-address f14-size t-color-y1"></text>
				<!-- 		<image src="@/static/images/task/icon-positioning.png"
							style="width: 16px;height: 16px;margin-right: 7.5px;"></image> -->
					</view>
					<view class="address">
						<text class="address-name">{{item.name}}</text>
						<text class="current-address">{{item.district}}{{item.address}}</text>
					</view>
					<view class="distance_text">
						<text>{{item.distance}}</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import amapFile from '@/utils/amap-wx.130.js';

	const API_KEY = '8c4969c9ce96c752dcc767bbfb54d748';

	import getlocation from '@/components/getlocation/index.vue';

	export default {
		data() {
			return {
				region:"请选择...",
				position:"",
				po_tips: '重新定位',
				timer: null,
				myAmapFun: null, // 高德获取地址
				keyword: '', // 用户输入的关键词
				searchResults: [], // 搜索提示结果
				historyList: [], // 历史记录
				gaodekey: 'key', // 高德的key
				currentname: "", // 地址标题
				currentaddress: "", // 已经获取到当前的位置
				city: '北京',
				addresstype: '',
				currentlat: '', // 当前位置纬度
				currentlng: '', // 当前位置经度
				currentdistancec: '', // 当前位置距离

			}
		},
		watch: {

			  city(newData){

			    this.searchTips()
			  }
		},
		onLoad(event) {
			this.myAmapFun = new amapFile.AMapWX({
				key:API_KEY
			});
			this.getMyLocation();
			this.historyList = JSON.parse(uni.getStorageSync('historylist') || '[]')
		},


		onShow() {
					const _this = this;
				uni.$on('region',function(data){
					console.log('监听到事件来自 region ，携带参数 msg 为：'  + data);
					_this.city = data;
				})
		},


		components: {
			getlocation,
		},
		methods: {
			// 获取当前位置
			getMyLocation() {
				const _this = this;
				const that = this;

				that.po_tips = '定位中...'

				that.mapfun.getlocation().then(res => {

						console.log("11111")
					that.mapfun.getCityinfo().then(res => {


							console.log( '当前定位111',res);
				            that.region =  res.addressComponent.province+res.addressComponent.city

							_this.city = res.addressComponent.city;

								// _this.currentname = `${data[0].desc}`
								_this.currentaddress = res.formatted_address


								let longitude =  uni.getStorageSync('longitude');
								let latitude = uni.getStorageSync('latitude');
								_this.currentlat = longitude // 当前位置纬度
								_this.currentlng = latitude // 当前位置经度
								_this.currentdistancec = _this.mapfun.getDistance(_this.currentlat, _this.currentlng, _this
									.currentlat, _this.currentlng, ) // 当前位置经度
								// uni.hideLoading();


					}).catch(err => {
							console.log("22222222222222222")
						// 		console.log(err, 'err')
						// 		uni.showToast({
						// 			title: "获取位置失败",
						// 			icon: "error"
						// 		})
								_this.currentname = "暂无当前位置信息111"
					})
				}).catch(err => {
					console.log("3333")

					// let latitude =  35.86166;
					// 	let longitude = 104.195397;
					let latitude = 30.651705;
					let longitude = 111.339805;
					uni.setStorageSync('longitude',longitude);
					uni.setStorageSync('latitude',latitude);

					that.mapfun.getCityinfo().then(res => {
							console.log(res)
						that.region =  res.addressComponent.province+res.addressComponent.city




								console.log(data, '当前定位');
								let longitude =  uni.getStorageSync('longitude');
								let latitude = uni.getStorageSync('latitude');

										_this.city = res.addressComponent.city;

									_this.currentaddress = res.formatted_address
								_this.currentlat = longitude // 当前位置纬度
								_this.currentlng = latitude // 当前位置经度
								_this.currentdistancec = _this.mapfun.getDistance(_this.currentlat, _this.currentlng, _this
									.currentlat, _this.currentlng, ) // 当前位置经度





								uni.hideLoading();


					}).catch(err => {
						// 		console.log(err, 'err')
						// 		uni.showToast({
						// 			title: "获取位置失败",
						// 			icon: "error"
						// 		})
								_this.currentname = "暂无当前位置信息"
					})



				})

					that.po_tips = '重新定位'

			},
			// 搜索地址
			searchTips() {
				if (this.keyword === '') {
					this.searchResults = []
					return
				}
				const _this = this;
				const that = this;
				// 发起搜索提示请求

				// that.mapfun.getInputtips().then(res => {
				// 					console.log("getInputtips11111")
				// }).catch(err => {
				// 	console.log("getInputtips2222")



				// })


				this.mapfun.getInputtips({
					keywords: this.keyword,
					city: this.city, //必须填写搜索的城市
					success(data) {
						if (data && data.tips) {
							const arr = JSON.parse(JSON.stringify(data.tips))
							for (let i of arr) {
								const str = i.location
								if (str.length !== 0) {
									const dis = str.split(',')
									const distance = _this.mapfun.getDistance(_this.currentlat,_this.currentlng, dis[1], dis[0])
									i.distance = distance
								}
							}
							arr.shift()
							_this.searchResults = arr;
							// console.log("_this.searchResults.",_this.searchResults)
						}
					},
				});

				// this.myAmapFun.getInputtips({
				// 	keywords: this.keyword,
				// 	city: this.city, //必须填写搜索的城市
				// 	success(data) {
				// 		if (data && data.tips) {
				// 			const arr = JSON.parse(JSON.stringify(data.tips))
				// 			for (let i of arr) {
				// 				const str = i.location
				// 				if (str.length !== 0) {
				// 					const dis = str.split(',')
				// 					const distance = _this.getDistances(_this.currentlat,_this.currentlng, dis[1], dis[0])
				// 					i.distance = distance
				// 				}
				// 			}
				// 			_this.searchResults = arr;
				// 		}
				// 	},
				// });
			},

			//搜索函数防抖
			input(e) {
				clearTimeout(this.timer)
				this.timer = setTimeout(() => {
					this.searchTips()
				}, 500)
			},
			// 选择地址
			checkdizhi(item,add) {
				if(add){
					this.saveSearchHistory(item) // 保存历史记录
				}
	            this.checkGo(item)

			},
			// 点击当前位置选择地址
			checkcurrent(item) {
				this.checkGo(item)


				// const address = item.district + item.address + item.name
				// 				console.log("item",item)
				// 				uni.navigateBack({
				// 					delta: 1 //返回上一页
				// 				})

				// if (this.addresstype == "startAddress") {
				// 	uni.$emit('startAddress', item)
				// 	uni.navigateBack({
				// 		delta: 1 //返回上一页
				// 	})
				// }
				// if (this.addresstype == "endAddress") {
				// 	uni.$emit('endAddress', item)
				// 	uni.navigateBack({
				// 		delta: 1 //返回上一页
				// 	})
				// }
			},
			checkGo(item){
				const address = item.district + item.address + item.name
								console.log("item",item)
								uni.navigateBack({
									delta: 1 //返回上一页
								})
			},
			// 清空搜索历史记录
			clearHistory() {
				uni.showModal({
					title: '提示',
					content: '是否清空搜索历史',
					success: (res) => {
						this.historyList = []
						uni.setStorageSync('historylist', '[]')
					}
				})
			},
			// 保存搜索历史并持久化
			saveSearchHistory(item) {
				this.historyList.unshift(item) // 把新数据添加到数组最后
				const string = this.historyList.map((index) => JSON.stringify(index)) // 把数组每一项转为字符串
				const removeDupList = Array.from(new Set(string)) //去重后再转为数组
				const result = removeDupList.map((item) => JSON.parse(item)) // 把数组每一项转为对象
				uni.setStorageSync('historylist', JSON.stringify(result))
			},
			// 改变城市
			changeCity() {
				uni.navigateTo({
					url: `/pages/task/area/selectregion`
				});
			},
		}
	}
</script>

<style lang="scss">

	.dingwei {
		width: 100%;
		padding-top: 25upx;
		box-sizing: border-box;
		margin-bottom: 26upx;
	}

	.dingwei_Tips {
		margin-left: 24upx;
		margin-bottom: 24upx;
		font-size: 24upx;
		color: #A5A5A5;
	}

	.dingwei_city {
		width: 100%;
		height: 60upx;
		padding-left: 55upx;
		padding-right: 70upx;
		box-sizing: border-box;
		display: flex;
		justify-content: space-between;
	}

	.dingwei_city_one {
		width: 185upx;
		height: 60upx;
		background-color: #ffffff;
		border-radius: 10upx;
		font-size: 32upx;
		color: #333333;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.dingweis_div {
		display: flex;
		align-content: flex-end;
		align-items: center;
		font-size: 24upx;
		color: #FD5745;
	}




	#container {
		width: 300px;
		height: 200px;
	}

	// 搜索栏
	.area-header {
		background-color: #fff;
		padding: 22px 16px 0 16px;

		.header-select {
			background-color: #F3F3F3;
			padding: 20rpx 5rpx;
			display: flex;
			flex-direction: row;
		    // align-items:stretch;
		  flex-grow: 1;
			// 左侧的城市名
			.select-region {

				flex:1;

				.region_text {
					font-size: 16px;
				}
			}

			// 右侧输入地址
			.select-input {
				width:100%;
				display: flex;
				flex-direction: row;
				flex:5;
				flex-grow: 2;
				justify-content: space-between;
				.input_holder {
					color: #D8D8D8;
					font-size: 16px;
				}
			}
		}
	}

	// 地址栏
	.position_ul {
		background-color: #fff;
		padding: 10px 20px;
		display: flex;
		align-items: center;
		border-bottom: 1px solid #F3F3F3;

		.address {
				flex: 5;

			.address-name {
				font-size: 16px;
			}

			.current-address {
				margin-top: 2px;
				font-size: 12px;
				color: #C0C4CC;
				display: flex;
				flex-direction: column;
			}
		}

		.distance_text {
			flex: 1;
			margin-left: 10px;
			font-size: 12px;
			color: #C0C4CC;
		}

		// 位置距离
		.site-distance {}
	}



 // 提示信息（当前位置/历史记录）
 .current_position {
 	padding: 12px 22px;
 	display: flex;
 	justify-content: space-between;
 	align-items: center;

 	.position_img {
 		width: 12px;
 		height: 12px;
 		margin-right: 7.5px;
 		line-height: 21px;
 		vertical-align: middle;
 	}

 	.position_text {
 		font-size: 12px;
 		color: #303133;
 		line-height: 21px;
 	}

 	// 清空历史
 	.clear_history {
 		font-size: 12px;
 		color: #2979FF;
 	}
 }


	// 选择地点历史记录
	.history-content {

		// 无历史记录提示信息
		.history_none {
			background-color: #fff;
			padding: 20px 10px;
			color: #C0C4CC;
		}

		// 提示信息（当前位置/历史记录）
		.current_position {
			padding: 12px 22px;
			display: flex;
			justify-content: space-between;
			align-items: center;

			.position_img {
				width: 12px;
				height: 12px;
				margin-right: 7.5px;
				line-height: 21px;
				vertical-align: middle;
			}

			.position_text {
				font-size: 12px;
				color: #303133;
				line-height: 21px;
			}

			// 清空历史
			.clear_history {
				font-size: 12px;
				color: #2979FF;
			}
		}
	}
</style>
